package com.synnapps.carouselview;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.PageSlider;

import ohos.app.Context;

import ohos.multimodalinput.event.TouchEvent;

/**
 * 自定义PageSlider
 */
public class CarouselViewPager extends PageSlider implements Component.TouchEventListener {
    private ImageClickListener imageClickListener;
    private float oldX = 0;
    private float newX = 0;
    private float sens = 5;

    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public CarouselViewPager(Context context) {
        this(context, null);
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrSet 资源集合
     */
    public CarouselViewPager(Context context, AttrSet attrSet) {
        super(context, attrSet);
        setTouchEventListener(this);
    }

    /**
     * 设置item点击事件
     *
     * @param imageClickListener 监听接口
     */
    public void setImageClickListener(ImageClickListener imageClickListener) {
        this.imageClickListener = imageClickListener;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent ev) {
        switch (ev.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                oldX = ev.getPointerPosition(0).getX();
                break;

            case TouchEvent.PRIMARY_POINT_UP:
                newX = ev.getPointerPosition(0).getX();
                if (Math.abs((double) oldX - (double) newX) < sens) {
                    if (imageClickListener != null) {
                        imageClickListener.onClick(getCurrentPage());
                    }
                    return true;
                }
                oldX = 0;
                newX = 0;
                break;
        }
        return true;
    }
}